package org.restql.db.operation;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.restql.db.Utility;
import org.restql.db.resource.DatabaseResource;
import org.restql.db.resource.ModifiableDatabaseResource;
import org.restql.db.resource.RequestResource;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DatabaseUpdate extends DatabasePutPost {

	private static Log logger = LogFactory.getLog(DatabaseUpdate.class);

	public DatabaseUpdate(DatabaseResource databaseResource, RequestResource requestResource) {
		super(databaseResource, requestResource);
	}

	// Node containing children of fields to update
	protected void doOperation(Node updateNode) throws SQLException {
		NodeList fields = updateNode.getChildNodes();
		List<String> fieldList = new ArrayList<String>();
		for (int i = 0; i < fields.getLength(); i++) {
			if (fields.item(i).getNodeType() == Node.ELEMENT_NODE) {
				fieldList.add(fields.item(i).getNodeName() + " = '" + fields.item(i).getTextContent() + "'");
			}
		}

		String constructedSQL =
			((ModifiableDatabaseResource) this.databaseResource).getUpdateString(this.requestResource) +
			" SET " + Utility.commas(fieldList) +
			this.databaseResource.getWhereString(this.requestResource);

		PreparedStatement stmt =
			getConnection().prepareStatement(constructedSQL);

		logger.info("Executing: " + constructedSQL);
		stmt.executeUpdate();
	}

}
